package xhwl.insurance.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lidroid.xutils.exception.DbException;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.android.common.log.XHLog;
import xhwl.android.common.util.IdcardValidator;
import xhwl.android.common.util.StringUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.BaseActivity;
import xhwl.insurance.R;
import xhwl.insurance.customView.ChineseEditText;
import xhwl.insurance.customView.PopSelectPic;
import xhwl.insurance.db.SaleInfoDao;
import xhwl.insurance.db.SalePicInfoDao;
import xhwl.insurance.db.bean.SaleInfo;
import xhwl.insurance.db.bean.SalePicInfo;
import xhwl.insurance.dialog.LoadingDialog;
import xhwl.insurance.dialog.SubmitFailureDialog;
import xhwl.insurance.event.SubmitInfoEvent;
import xhwl.insurance.http.api.SaleInfoApi;
import xhwl.insurance.http.api.SubmitFileApi;
import xhwl.insurance.http.api.UploadPicApi;
import xhwl.insurance.http.bean.ImageEvent;
import xhwl.insurance.http.bean.ImageItem;
import xhwl.insurance.http.bean.ReferralPicBean;
import xhwl.insurance.http.bean.resp.ErrorCode;
import xhwl.insurance.http.bean.resp.SaleInfoResp;
import xhwl.insurance.util.AppUtil;
import xhwl.insurance.util.ImageDisplayer;
import xhwl.insurance.util.IntentConstants;
import xhwl.insurance.util.NumberJudgeUtils;
import xhwl.insurance.util.PermisionUtils;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;


public class SubmitSaleInfoActivity extends BaseActivity implements OnClickListener, PopSelectPic.PopSelectBtnClickListener {
    private static final String TAG = SubmitSaleInfoActivity.class.getSimpleName();
    int Year;
    String person_sex;
    EditText  phone;
    ChineseEditText name;
    EditText number;
    Button btnBasicInfoNext,btnIDCardNext,btnHmoSubmit;
    LinearLayout llBasic,llIDCard,llHMOCard;

    LinearLayout addPaitenetLayout;
    TextView tvDesc;
    EditText card_num;

//    private static String[] PERMISSION = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private String path;
    private File file1,file2,file3;
    private ImageView id_front,id_back,hmo_pic,iv_info_progress1,iv_info_progress2,iv_info_progress3,iv_info_progress4;
    private int flag;
    private static final int TAKE_PICTURE = 0x000000;
    private TextView card_name;
    String cardprice,yw_id,saletype,card_names,c_type;
    SaleInfo saleInfo;
    SaleInfoDao saleInfoDao;
    SalePicInfoDao salePicInfoDao;
    boolean autoSubmit;//是否自动提交
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==0){//上传图片结果回调
                //此时图片全部处理完成，有可能全部成功或部分成功
                if(autoSubmit){//点击提交按钮在前，图片上传完成在后
                    updateDialogMsg();
                    SalePicInfo.UploadStatus uploadStatus= checkPicStatus();//检查图片是否上传完成，可能情况，完成，失败
                    if(SalePicInfo.UploadStatus.START!=uploadStatus) {
                        //当前有上传中的图片，继续等待
                        dismissDialog();
                        updateFiles();
                    }
                }

            }
        }
    };
    private void cacheData(int status){
        long createTime=System.currentTimeMillis();
        saleInfo.card_name=card_names;
        saleInfo.yw_id=yw_id;
        saleInfo.c_type=c_type;
        saleInfo.sale_type=saletype;
        saleInfo.card_price=cardprice;

        saleInfo.create_time=createTime;
        saleInfo.status=status;
        try {
            saleInfoDao.saveBindingId(saleInfo);
            Collection<SalePicInfo> list=saleInfo.picInfoMap.values();
            for(SalePicInfo info:list){
                info.sale_id=saleInfo.id;
                info.create_time=createTime;
                salePicInfoDao.saveBindingId(info);
            }
            Log.e("saleInfo",saleInfo.toString());
        } catch (DbException e) {
            e.printStackTrace();
        }

    }
    private void showFailDialog(){
        final SubmitFailureDialog pd = new SubmitFailureDialog(SubmitSaleInfoActivity.this);
        pd.setCancelable(false);
        pd.setCanceledOnTouchOutside(false);
        if(!SubmitSaleInfoActivity.this.isFinishing()){
            pd.show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    pd.dismiss();
                    AppUtil.startDealListPage(mContext,4);
                    finish();
                }
            }, 5000);

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        saleInfoDao=new SaleInfoDao(mContext);
        salePicInfoDao=new SalePicInfoDao(mContext);
        cardprice = getIntent().getStringExtra("cardprice");//价格id_front
        yw_id = getIntent().getStringExtra("yw_id");
        saletype = getIntent().getStringExtra("saletype");
        card_names = getIntent().getStringExtra("card_name");
        c_type = getIntent().getStringExtra("c_type");
        setContentView(R.layout.activity_submit_sale_info);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initViews() {
        initTitleViews();
        llBasic= (LinearLayout) findViewById(R.id.llBasic);
        llIDCard= (LinearLayout) findViewById(R.id.llIDCard);
        llHMOCard= (LinearLayout) findViewById(R.id.llHMOCard);

        addPaitenetLayout = (LinearLayout) findViewById(R.id.addpaitenetlayout);
        name = (ChineseEditText) findViewById(R.id.add_paitent_name);
        number = (EditText) findViewById(R.id.add_paitent_number);
        phone = (EditText) findViewById(R.id.add_paitent_phone);
        card_name = (TextView) findViewById(R.id.card_name);
        tvDesc = (TextView) findViewById(R.id.tvDesc);
        card_num = (EditText) findViewById(R.id.card_num);
        id_front = (ImageView) findViewById(R.id.id_front);
        id_back = (ImageView) findViewById(R.id.id_back);
        hmo_pic = (ImageView) findViewById(R.id.hmo_pic);
        btnBasicInfoNext= (Button) findViewById(R.id.btnBasicInfoNext);
        btnIDCardNext= (Button) findViewById(R.id.btnIDCardNext);
        btnHmoSubmit= (Button) findViewById(R.id.btnHmoSubmit);
        iv_info_progress1= (ImageView) findViewById(R.id.iv_info_progress1);
        iv_info_progress2= (ImageView) findViewById(R.id.iv_info_progress2);
        iv_info_progress3= (ImageView) findViewById(R.id.iv_info_progress3);
        iv_info_progress4= (ImageView) findViewById(R.id.iv_info_progress4);
        tvDesc.setText(R.string.hmocardsalenotice);
        card_name.setText(card_names);
    }

    @Override
    public void initListener() {
        // TODO Auto-generated method stub
        btnBasicInfoNext.setOnClickListener(this);
        btnIDCardNext.setOnClickListener(this);
        btnHmoSubmit.setOnClickListener(this);
        id_front.setOnClickListener(this);
        id_back.setOnClickListener(this);
        hmo_pic.setOnClickListener(this);

        number.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                if (s.length() == 18) {
                    String idNumber = s.toString();
                    String returnMsg = IdcardValidator.validate18Idcard(idNumber);
                    if (StringUtil.isEmpty(returnMsg)) {
                        try {
                            String strYear = idNumber.substring(6, 10);// 年份
                            String strMonth = idNumber.substring(10, 12);// 月份
                            String strDay = idNumber.substring(12, 14);// 月份
//                            date.setText(strYear + "-" + strMonth + "-" + strDay);
                            Year = Integer.parseInt(strYear);
                            String sexStr = idNumber.substring(15, 17);
                            int sex = Integer.parseInt(sexStr);
                            if (sex % 2 == 0) {
                                person_sex = "1";
                            } else {
                                person_sex = "0";
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            ToastUtil.showToast(mContext, e.getMessage());
                        }
                    } else {
                        ToastUtil.showToast(mContext, returnMsg);
                    }
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()==11&&!NumberJudgeUtils.isMobileNO(phone.getText().toString())) {
                    ToastUtil.showToast(mContext,"手机号格式错误，请输入正确的手机号");
                }
            }
        });
    }

    @Override
    protected void setUpTitleView() {
        // TODO Auto-generated method stub
        super.setUpTitleView();
//        titleTextView.setText("售卡信息");
    }
    @Override
    protected void processOper() {
        // TODO Auto-generated method stub
        showPage(0);
        saleInfo=new SaleInfo();
        for(SalePicInfo.PicType picType:SalePicInfo.PicType.values()){
            SalePicInfo salePicInfo=new SalePicInfo();
            saleInfo.picInfoMap.put(picType.ordinal(),salePicInfo);
        }
        getSaleInfo();
    }
    void getSaleInfo() {
        SaleInfoApi api = new SaleInfoApi();
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<SaleInfoResp>() {
            @Override
            public void onNext(SaleInfoResp resp) {
                saleInfo.saler_user_id = resp.user_id;
                saleInfo.saler_mobile = resp.link_mobile;
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
//                ToastUtil.showToast(mContext,"销售人信息不能为空，请重新请求网络");
                ToastUtil.showToast(mContext,"请求超时，请重新请求网络");
            }
        });
    }

    int curPage=0;
    private void showPage(int page){
        curPage=page;
        switch(page){
            case 0:
                llBasic.setVisibility(View.VISIBLE);
                llIDCard.setVisibility(View.GONE);
                llHMOCard.setVisibility(View.GONE);
                titleTextView.setText("基本信息");

                break;
            case 1:
                llBasic.setVisibility(View.GONE);
                llIDCard.setVisibility(View.VISIBLE);
                llHMOCard.setVisibility(View.GONE);
                titleTextView.setText("身份信息");

                break;
            case 2:
                llBasic.setVisibility(View.GONE);
                llIDCard.setVisibility(View.GONE);
                llHMOCard.setVisibility(View.VISIBLE);
                titleTextView.setText("售卡信息");
                break;
            default:
                break;
        }
    }
    @Override
    public void loadData() {
        // TODO Auto-generated method stub
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.id_front:
                flag = 1;
                PopSelectPic popfront = new PopSelectPic(this, id_front);
                popfront.setCallBack(this);
                break;
            case R.id.id_back:
                flag = 2;
                PopSelectPic popback = new PopSelectPic(this, id_back);
                popback.setCallBack(this);
                break;
            case R.id.hmo_pic:
                flag = 3;
                PopSelectPic pophmo = new PopSelectPic(this, id_back);
                pophmo.setCallBack(this);
                break;
            case R.id.btnBasicInfoNext:
                String msg="";
                if (TextUtils.isEmpty(name.getText())) {
                    msg = "姓名输入不能为空";
                } else if (TextUtils.isEmpty(phone.getText())) {
                    msg = "手机号输入不能为空";
                } else if (phone.getText().toString().length() != 11) {
                    msg = "手机号为11位数字，请输入正确的手机号";
                } else if (false == NumberJudgeUtils.isMobileNO(phone.getText().toString())) {
                    msg = "手机号格式错误，请输入正确的手机号";
                }
                if(!StringUtil.isEmpty(msg)){
                    ToastUtil.showToast(mContext,msg);
                    return;
                }
                saleInfo.person_name=name.getText().toString();
                saleInfo.person_mobile=phone.getText().toString();

                showPage(1);
                break;
            case R.id.btnIDCardNext:
                String msg2="";
                if (StringUtil.isEmpty(number.getText().toString())) {
                    msg2 = "身份证号码不能为空";
                } else if (!StringUtil.isEmpty(IdcardValidator.validate18Idcard(number.getText().toString()))) {
                    msg2 = IdcardValidator.validate18Idcard(number.getText().toString());
                }else if (null == file1 || "".equals(file1.getPath())) {
                    msg2 = "身份证正面照片不能为空，请上传身份证正面照片";
                } else if (null == file2 || "".equals(file2.getPath())) {
                    msg2 = "身份证背面照片不能为空，请上传身份证背面照片";
                }
                if(!StringUtil.isEmpty(msg2)){
                    ToastUtil.showToast(mContext,msg2);
                    return;
                }
                saleInfo.id_card_number=number.getText().toString();
                showPage(2);
                break;
            case R.id.btnHmoSubmit:
                String msg3="";
                if (StringUtil.isEmpty(card_num.getText().toString())) {
                    msg3 = "HMO卡卡号不能为空";
                }else if (null == file3 || "".equals(file3.getPath())) {
                    msg3 = "卡号照片不能为空，请上传卡号照片";
                }else if(StringUtil.isEmpty(saleInfo.saler_user_id)||StringUtil.isEmpty(saleInfo.saler_mobile)){
//                    msg3="销售人信息不能为空，请重新请求网络";
                    msg3="请求超时，请重新请求网络";
                }

                if(!StringUtil.isEmpty(msg3)){
                    ToastUtil.showToast(mContext,msg3);
                    return;
                }
//                btnHmoSubmit.setEnabled(false);

                saleInfo.card_name=card_names;
                saleInfo.card_number=card_num.getText().toString();
                SalePicInfo.UploadStatus uploadStatus= checkPicStatus();
                if(SalePicInfo.UploadStatus.SUCCESS==uploadStatus){//图片全部上传完成
                    updateFiles();
                }else {
                    //有图片正在上传
                    autoSubmit=true;//等待
                    showDialog();
                    //有上传失败的情况
                    if(SalePicInfo.UploadStatus.FAIL==uploadStatus){
                        Collection<SalePicInfo> values = saleInfo.picInfoMap.values();
                        List<File> failList=new ArrayList<>();
                        for(SalePicInfo info:values){
                            if(info.status==SalePicInfo.UploadStatus.FAIL.ordinal()){
                                if(info.pic_type==SalePicInfo.PicType.ID_CARD_FORNT.ordinal()){
                                    failList.add(file1);
                                }else if(info.pic_type==SalePicInfo.PicType.ID_CARD_BACK.ordinal()){
                                    failList.add(file2);
                                }else if(info.pic_type==SalePicInfo.PicType.HMO_CARD_FORNT.ordinal()){
                                    failList.add(file3);
                                }
                            }
                        }
                        uploadPic(failList);
                    }

                }
                break;

            default:
                break;
        }
    }
    private String getCountMsg(){
        int successCount=0;
        Collection<SalePicInfo> values = saleInfo.picInfoMap.values();
        for(SalePicInfo info:values){
            if(SalePicInfo.UploadStatus.SUCCESS.ordinal()==info.status){
                successCount++;
            }
        }
        if(successCount==0){
            return "请稍候...";
        }
        return "请稍候"+successCount+"/"+values.size();
    }
    LoadingDialog dialog;
    private void showDialog(){

        dialog=new LoadingDialog(mContext,getCountMsg());
//        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                autoSubmit=false;//等待上传图片过程中，用户取消对话框以后，不再继续提交，用户可以再次点提交按钮
            }
        });
        dialog.show();
    }
    private void updateDialogMsg(){
        if(dialog!=null&&dialog.isShowing()){
            dialog.setText(getCountMsg());
        }
    }
    private void dismissDialog(){
        if(dialog!=null&&dialog.isShowing()){
            dialog.dismiss();
        }
    }
    private SalePicInfo.UploadStatus checkPicStatus(){
        xhwl.insurance.util.XHLog.e(saleInfo.picInfoMap.toString());
        Collection<SalePicInfo> values = saleInfo.picInfoMap.values();
        int successCount=0;
        boolean isUploading=false;
        for(SalePicInfo info:values){
            if(SalePicInfo.UploadStatus.START.ordinal()==info.status){
                isUploading=true;
            }else if(SalePicInfo.UploadStatus.SUCCESS.ordinal()==info.status){
                successCount++;
            }
        }

        if(isUploading){
            return SalePicInfo.UploadStatus.START;
        }
        if(successCount==values.size()){
            return SalePicInfo.UploadStatus.SUCCESS;
        }
        else
        {
            return SalePicInfo.UploadStatus.FAIL;
        }
    }

    @Override
    public void onBackPressed() {
        if(curPage==0){
            super.onBackPressed();
        }else
        {
            showPage(curPage-1);
        }

    }

    private int getPicType(File file) {
        if (file == file1) {
            return SalePicInfo.PicType.ID_CARD_FORNT.ordinal();
        } else if (file == file2) {
            return SalePicInfo.PicType.ID_CARD_BACK.ordinal();
        }else if (file == file3) {
            return SalePicInfo.PicType.HMO_CARD_FORNT.ordinal();
        }
        throw new IllegalArgumentException("参数异常");
    }
    private void uploadPic(final List<File> fileList){
        if(fileList==null||fileList.size()==0)
            return;

        final UploadPicApi api = new UploadPicApi(mContext, false,fileList.toArray(new File[fileList.size()]));
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ArrayList<ReferralPicBean>>() {
            @Override
            public void onStart() {
                super.onStart();
                for(File file:fileList){
                    Integer type=getPicType(file);
                    SalePicInfo picInfo=saleInfo.picInfoMap.get(type);
                    picInfo.pic_type=type;
                    picInfo.status=SalePicInfo.UploadStatus.START.ordinal();
                    picInfo.save_path=file.getPath();
                }
            }

            @Override
            public void onNext(ArrayList<ReferralPicBean> picBeanList) {
                for(int i=0;i<fileList.size();i++) {
                    Integer type=getPicType(fileList.get(i));
                    SalePicInfo picInfo=saleInfo.picInfoMap.get(type);
                    picInfo.url=picBeanList.get(i).getUrl_big();
                    picInfo.status=SalePicInfo.UploadStatus.SUCCESS.ordinal();
                }
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                for(File file:fileList) {
                    Integer type = getPicType(file);
                    SalePicInfo picInfo = saleInfo.picInfoMap.get(type);
                    picInfo.status = SalePicInfo.UploadStatus.FAIL.ordinal();
                }
                handler.sendEmptyMessage(0);
            }
        });
    }
    private void uploadPic(final File file){
        if(file==null)
            return;
        final Integer type=getPicType(file);
        final SalePicInfo picInfo=saleInfo.picInfoMap.get(type);

        final UploadPicApi api = new UploadPicApi(mContext, false,new File[]{file});
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ArrayList<ReferralPicBean>>() {
            @Override
            public void onStart() {
                super.onStart();
                picInfo.pic_type=type;
                picInfo.status=SalePicInfo.UploadStatus.START.ordinal();
                picInfo.save_path=file.getPath();
                xhwl.insurance.util.XHLog.e(type+"开始上传..");
            }

            @Override
            public void onNext(ArrayList<ReferralPicBean> picBeanList) {
                picInfo.url=picBeanList.get(0).getUrl_big();
                picInfo.status=SalePicInfo.UploadStatus.SUCCESS.ordinal();
                xhwl.insurance.util.XHLog.e(type+"上传成功");
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                picInfo.status=SalePicInfo.UploadStatus.FAIL.ordinal();
                xhwl.insurance.util.XHLog.e(type+"上传失败");
                handler.sendEmptyMessage(0);
            }
        });
    }

    private void updateFiles() {


        SalePicInfo.UploadStatus uploadStatus= checkPicStatus();
        if(SalePicInfo.UploadStatus.SUCCESS!=uploadStatus){//图片没有全部上传完成
            cacheData(SaleInfo.Status.FAIL.ordinal());
            EventBus.getDefault().post(new SubmitInfoEvent(true));
            showFailDialog();
            return;
        }
        String card_front=saleInfo.picInfoMap.get(SalePicInfo.PicType.ID_CARD_FORNT.ordinal()).url;
        String card_back=saleInfo.picInfoMap.get(SalePicInfo.PicType.ID_CARD_BACK.ordinal()).url;
        String card_number_pic=saleInfo.picInfoMap.get(SalePicInfo.PicType.HMO_CARD_FORNT.ordinal()).url;

        String sale_date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
        int currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date(System.currentTimeMillis())));
        String age = String.valueOf(currentYear - Year);

        SubmitFileApi api = new SubmitFileApi(c_type, age, number.getText().toString(), phone.getText().toString(),
                name.getText().toString(), person_sex, saleInfo.saler_mobile, saletype, saleInfo.saler_user_id,
                yw_id, card_num.getText().toString(), card_number_pic,
                cardprice, card_front, card_back, sale_date);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ErrorCode>() {
            @Override
            public void onNext(ErrorCode resp) {
                if (resp.getError_code().equals("ok")) {
                    ToastUtil.showToast(mContext, "提交资料成功");
                    cacheData(SaleInfo.Status.SUCCESS.ordinal());
                    EventBus.getDefault().post(new SubmitInfoEvent(true));

                    iv_info_progress3.setVisibility(View.GONE);
                    iv_info_progress4.setVisibility(View.VISIBLE);
                    AppUtil.startDealListPage(mContext,1);
                    finish();

                } else {
                    if ("00046".equals(resp.getError_code())) {
                        ToastUtil.showToast(mContext, "卡号不存在或卡已被绑定");
                    } else if ("00048".equals(resp.getError_code())) {
                        ToastUtil.showToast(mContext, "该卡为预售不可退，您无权限绑定");
                    } else if ("00049".equals(resp.getError_code())) {
                        ToastUtil.showToast(mContext, "该套装的卡号不存在或已绑定");
                    }else {
                        ToastUtil.showToast(mContext, "提交资料失败,请重新点击提交");

                    }
                }
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                cacheData(SaleInfo.Status.FAIL.ordinal());
                EventBus.getDefault().post(new SubmitInfoEvent(true));
                showFailDialog();
            }
        });
    }


    @Override
    public void onTakePhotoClick() {
        takePhoto();
    }

    @Override
    public void onSelectPicClick() {
        pickPicture();
    }

    private void pickPicture() {
//        if (PermisionUtils.islacksOfPermission(this, PERMISSION[1])) {
//            ToastUtil.showToast(this, "请打开提示对应权限,否则将无法选择您的照片");
//            ActivityCompat.requestPermissions(this, PERMISSION, 1);
//        } else {
//            Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
//            intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 1);
//            startActivity(intent);
//        }

        //2017.11.21权限替换 后期测试没有问题删除注释liujin
        requestPermission();
    }

    private void requestPermission() {
        new RxPermissions(this).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
              Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
            intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 1);
            startActivity(intent);
                } else {
                    Log.e(TAG, "用户拒绝开启权限");
                    PermisionUtils.dialog(SubmitSaleInfoActivity.this, "用户拒绝开启权限");
                }
            }
        });


    }


    public void takePhoto() {
//        if (PermisionUtils.islacksOfPermission(SubmitSaleInfoActivity.this, PERMISSION[0])) {
//            ToastUtil.showToast(this, "请打开提示对应权限,否则将影响拍照功能无法使用");
//            ActivityCompat.requestPermissions(this, PERMISSION, 0);
//        } else {
//            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//            File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
//            if (!vFile.exists()) {
//                File vDirPath = vFile.getParentFile();
//                vDirPath.mkdirs();
//            } else {
//                if (vFile.exists()) {
//                    vFile.delete();
//                }
//            }
//            path = vFile.getPath();
//            Uri cameraUri;
//            if (Build.VERSION.SDK_INT >= 24) {
//                cameraUri = FileProvider.getUriForFile(this.getApplicationContext(), "xhwl.insurance.fileProvider", vFile);
//            } else {
//                cameraUri = Uri.fromFile(vFile);
//            }
//            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
//            startActivityForResult(openCameraIntent, TAKE_PICTURE);
//        }
        //2017.11.21权限替换 后期测试没有问题删除注释liujin
        requestTakePicPermission();
    }

    private void requestTakePicPermission() {
        new RxPermissions(this).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
                    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
                    if (!vFile.exists()) {
                        File vDirPath = vFile.getParentFile();
                        vDirPath.mkdirs();
                    } else {
                        if (vFile.exists()) {
                            vFile.delete();
                        }
                    }
                    path = vFile.getPath();
                    Uri cameraUri;
                    if (Build.VERSION.SDK_INT >= 24) {
                        cameraUri = FileProvider.getUriForFile(getApplicationContext(), "xhwl.insurance.fileProvider", vFile);
                    } else {
                        cameraUri = Uri.fromFile(vFile);
                    }
                    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
                    startActivityForResult(openCameraIntent, TAKE_PICTURE);

                } else {
                    Log.e(TAG, "请打开提示对应权限,否则将影响拍照功能无法使用");
                    PermisionUtils.dialog(SubmitSaleInfoActivity.this, "请打开提示对应权限,否则将影响拍照功能无法使用");
                }
            }
        });
    }

    public void onEvent(ImageEvent event) {
        if (event == null)
            return;

        Collection<ImageItem> collection = event.getCollection();

        for (ImageItem item : collection) {// 目前只能选择一张图片，可上传多张图片时，需根据接口定义修改s
            XHLog.e("sourcePath=" + item.getSourcePath());
            initImageFiles(item);
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKE_PICTURE&&resultCode==RESULT_OK) {
            ImageItem item = new ImageItem();
            item.sourcePath = path;
            XHLog.e("sourcePath=" + item.sourcePath);
            initImageFiles(item);
        }
    }
    private void initImageFiles(ImageItem item){
        String fileName=xhwl.insurance.util.BitmapUtil.handleImage(mContext,item.sourcePath,200);
        if (flag == 1) {
            file1 = new File(fileName);
            ImageDisplayer.getInstance(mContext).displayBmp(id_front, item.thumbnailPath, item.sourcePath);
            uploadPic(file1);
        } else if (flag == 2) {
            file2 = new File(fileName);
            ImageDisplayer.getInstance(mContext).displayBmp(id_back, item.thumbnailPath, item.sourcePath);
            uploadPic(file2);
        } else if (flag == 3) {
            file3 = new File(fileName);
            ImageDisplayer.getInstance(mContext).displayBmp(hmo_pic, item.thumbnailPath, item.sourcePath);
            uploadPic(file3);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        //清空缓存的图片
//        DataCleanManager.deleteFilesByDirectory(new File(mContext.getCacheDir().getAbsolutePath()+ File.separator+"image"));
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takePhoto();
                } else {
                    ToastUtil.showToast(this, "请您打开本应用的拍照权限,否则将无法拍照");
                }
                break;
            case 1:
                if (grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    pickPicture();
                } else {
                    ToastUtil.showToast(this, "请您打开本应用的读取存储权限,否则将无法获取相册照片");
                }
                break;
        }
    }
}
